package com.deerblock;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.deerblock.config.ResponseStruct;
import com.deerblock.share.views.AuthAdapter;
import com.deerblock.utils.CountDownTimerUtils;
import com.deerblock.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.shareboard.SnsPlatform;

import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentSkipListMap;

import okhttp3.Call;
import okhttp3.Response;

public class LoginActivity extends Activity {
  private final String TAG = LoginActivity.class.getSimpleName();
  private ListView listView;
  private AuthAdapter shareAdapter;
  public ArrayList<SnsPlatform> platforms = new ArrayList<SnsPlatform>();
  private SHARE_MEDIA[] list = {SHARE_MEDIA.WEIXIN,SHARE_MEDIA.SINA,SHARE_MEDIA.QQ};
  private ProgressDialog dialog;
  private Button getCodeButton;
  private Button loginButton;
  private CountDownTimerUtils countDown;
  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    initViews();
    initEvents();
  }

  private void initViews(){
    dialog = new ProgressDialog(this);
//    listView = findViewById(R.id.list);
    initPlatforms();
//    shareAdapter = new AuthAdapter(this,platforms);
//    listView.setAdapter(shareAdapter);

    // 初始化checkbox文本
    TextView policyTextView = findViewById(R.id.policy);
    String policyText = getResources().getString(R.string.policy_text);
    Spanned htmlString = Html.fromHtml(policyText);
    if(htmlString instanceof SpannableStringBuilder){
      SpannableStringBuilder spannableStringBuilder = (SpannableStringBuilder) htmlString;
      Object[] objs = spannableStringBuilder.getSpans(0,spannableStringBuilder.length(), URLSpan.class);
      LoginActivity context = this;
      for(Object obj:objs){
        int start = spannableStringBuilder.getSpanStart(obj);
        int end = spannableStringBuilder.getSpanEnd(obj);
        URLSpan span = (URLSpan) obj;
        final String url =span.getURL();
        spannableStringBuilder.removeSpan(obj);
        spannableStringBuilder.setSpan(new ClickableSpan() {
          @Override
          public void onClick(@NonNull View view) {
            Intent intent = new Intent(LoginActivity.this, WebviewActivity.class);
            intent.putExtra("url", url);
            startActivity(intent);
          }

          @Override
          public void updateDrawState(@NonNull TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(getResources().getColor(R.color.colorBtn));
            ds.setUnderlineText(false);
          }
        },start,end,Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
      }
      policyTextView.setText(spannableStringBuilder);
    }
//    policyTextView.setText(Html.fromHtml(policyText));
//    policyTextView.setClickable(true);
    policyTextView.setMovementMethod(LinkMovementMethod.getInstance());

    //设置edittext hint 颜色
    EditText codeInput = findViewById(R.id.et_code);
    EditText phoneInput = findViewById(R.id.et_number);
    int c = getResources().getColor(R.color.colorInput);
    codeInput.setHintTextColor(c);
    phoneInput.setHintTextColor(c);
  }



  private void initEvents(){
    getCodeButton = findViewById(R.id.get_code_btn);
    EditText codeInput = findViewById(R.id.et_code);
    EditText phoneInput = findViewById(R.id.et_number);
    loginButton = findViewById(R.id.login_btn);
    CheckBox agreeBox = findViewById(R.id.cb_agree);


    phoneInput.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

      }

      @Override
      public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

      }

      @Override
      public void afterTextChanged(Editable editable) {
         int len = editable.toString().length();
        getCodeButton.setEnabled(len>=11);
      }
    });

    codeInput.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

      }

      @Override
      public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

      }

      @Override
      public void afterTextChanged(Editable editable) {
        Integer len = editable.toString().length();
        Integer phoneTextLen =  phoneInput.getText().length();
        loginButton.setEnabled((len>=6&&phoneTextLen>=11));
      }
    });

    getCodeButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        ConcurrentSkipListMap<String, String> reqBody = new ConcurrentSkipListMap<>();
        String phoneNumber = phoneInput.getText().toString();
        reqBody.put("phone_number",phoneNumber);
        NetUtils netUtils = NetUtils.getInstance();
        netUtils.postDataAsynToNet(BuildConfig.API_HOST.concat("/msg/phone_valid/"), reqBody, new NetUtils.MyNetCall() {
          @Override
          public void success(Call call, Response response) throws IOException {
            String result = response.body().string();
            Log.i(TAG,result+"");
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                try {
                  Gson json = new Gson();
                  ResponseStruct res = json.fromJson(result,ResponseStruct.class);
                  if(res.code == 0){ //TODO 数据结构调整
                    Toast.makeText(LoginActivity.this,"验证码已发出，请注意查收", Toast.LENGTH_LONG).show();
                    countDown = new CountDownTimerUtils(getCodeButton,60000,1000);
                    countDown.start();
                  }else{
                    Toast.makeText(LoginActivity.this,res.message.isEmpty()?res.error:res.message,Toast.LENGTH_LONG).show();
                  }
                } catch (Exception e){
                  e.printStackTrace();
                }
              }
            });

          }

          @Override
          public void failed(Call call, IOException e) {
            Log.e(TAG,e.toString());
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                Toast.makeText(LoginActivity.this,"请求出错，请联系客服",Toast.LENGTH_SHORT).show();
              }
            });
          }
        });
      }
    });
    loginButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        if(!agreeBox.isChecked()){
          Toast.makeText(LoginActivity.this,"请先阅读服务协议及隐私保护，同意后继续",Toast.LENGTH_SHORT).show();
          return;
        }

        String codeInputText = codeInput.getText().toString();
        String phoneNumber = phoneInput.getText().toString();
        ConcurrentSkipListMap<String, String> reqBody = new ConcurrentSkipListMap<>();
        reqBody.put("phone_number",phoneNumber);
        reqBody.put("validate_code", codeInputText);
        reqBody.put("username","");
        NetUtils netUtils = NetUtils.getInstance();
        netUtils.postDataAsynToNet(BuildConfig.API_HOST.concat("/register/"),reqBody, new NetUtils.MyNetCall(){
          @Override
          public void success(Call call, Response response) throws IOException {
            String result = response.body().string();
            Log.i(TAG,result+"");
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                try {
                  Gson json = new Gson();
                  ResponseStruct res = json.fromJson(result,ResponseStruct.class);
                  if(res.code==0){
                    countDown.cancel();
                    Intent pIntent = new Intent();
                    pIntent.putExtra("result",result);
                    setResult(1,pIntent);
                    finish();
                  }else {
                    Toast.makeText(LoginActivity.this,res.message.isEmpty()?res.error:res.message,Toast.LENGTH_LONG).show();
                  }
                }catch (Exception e){
                  e.printStackTrace();
                }

              }
            });
          }

          @Override
          public void failed(Call call, IOException e) {
            e.printStackTrace();
            call.cancel();
            Toast.makeText(LoginActivity.this,"请求异常",Toast.LENGTH_LONG).show();
          }
        });
      }
    });
  }

  private void initPlatforms(){
    platforms.clear();
    for(SHARE_MEDIA e:list){
      if(!e.toString().equals(SHARE_MEDIA.GENERIC.toString())){
        platforms.add(e.toSnsPlatform());
      }
    }
  }


  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    UMShareAPI.get(this).release();

  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    UMShareAPI.get(this).onSaveInstanceState(outState);
  }
}
